package com.topsun.framework.common.core.util;

import cn.hutool.core.collection.CollUtil;
import com.topsun.framework.common.core.enums.GlobalErrorCodeEnum;
import com.topsun.framework.common.core.exception.BusinessException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Collection;
import java.util.Set;

/**
 * 校验工具类
 */
public class ValidationUtils {
    private static final Validator validator =  Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 具体类
     */
    public static <T> ValidationResult validateEntity(T obj){
        ValidationResult result = new ValidationResult();
        Set<ConstraintViolation<T>> set = validator.validate(obj,Default.class);
        if(CollUtil.isNotEmpty(set) ){
            result.setHasErrors(true);
            for(ConstraintViolation<T> cv : set){
                result.getErrorMsg().put(cv.getPropertyPath().toString(), cv.getMessage());
            }
        }
        return result;
    }

    /**
     * 具体相关字段
     */
    public static <T> ValidationResult validateProperty(T obj, String propertyName){
        ValidationResult result = new ValidationResult();
        Set<ConstraintViolation<T>> set = validator.validateProperty(obj,propertyName,Default.class);
        if(CollUtil.isNotEmpty(set) ){
            result.setHasErrors(true);
            for(ConstraintViolation<T> cv : set){
                result.getErrorMsg().put(propertyName, cv.getMessage());
            }
        }
        return result;
    }

    /**
     * 校验参数，抛出异常
     * @param object 校验的参数对象
     */
    public static void validateEntityThrowErrorMsg(Object object) {
        ValidationResult validationResult = validateEntity(object);
        if (validationResult.isHasErrors()) {
            throw new BusinessException(GlobalErrorCodeEnum.PARAM_ERROR.getCode(), validationResult.getErrorMessage());
        }
    }

    /**
     * 校验参数，抛出异常
     */
    public static void validateEntityThrowErrorMsg(Collection<?> collection) {
        if (CollUtil.isEmpty(collection)) {
            return;
        }
        collection.forEach(ValidationUtils::validateEntityThrowErrorMsg);
    }

}
